/**
 * Project Name:springBoot-serviceImpl
 * File Name:RedisService.java
 * Package Name:com.libra.serviceImp
 * Date:2018年8月11日下午2:22:17
 * Copyright (c) 2018, wangzhch All Rights Reserved.
 *
*/

package com.libra.serviceImp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Service;

import com.libra.model.redis.Student;
import com.libra.model.vo.ResponseData;

import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 
 * ClassName: RedisService <br/>
 * Function: TODO ADD FUNCTION. <br/>
 * Reason: TODO ADD REASON(可选). <br/>
 * date: 2018年8月11日 下午2:23:02 <br/>
 *
 * @author wangzhch
 * @version 
 * @since JDK 1.8
 */
@Service
public class RedisServiceImp {
	Logger log = LoggerFactory.getLogger(RedisServiceImp.class);
	
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 写入缓存
     * @param key
     * @param value
     * @return
     */
    public ResponseData writeCache(final String key, Object value) {
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            return ResponseData.success("写入缓存成功");
        } catch (Exception e) {
        	log.error(e.getMessage());
            return ResponseData.error(e.getMessage());
        }
        
    }
    /**
     * 写入缓存设置时效时间
     * @param key
     * @param value
     * @return
     */
    public ResponseData wrightCaheByExpireTime(final String key, Object value, Long expireTime) {
    	ResponseData responseData = ResponseData.success();
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            return ResponseData.success("写入缓存成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResponseData.error(e.getMessage());
        }
    }
    /**
     * 批量删除对应的value
     * @param keys
     * @return 
     */
    public ResponseData deleteBatchValue(final String... keys) {
    	ResponseData responseData = ResponseData.success();
    	int num = 0;
        for (String key : keys) {
        	if(remove(key)) {
        		num++;
        	}
        }
        log.info("删除成功个数:{}",num);
        if(num>0) {
        	return ResponseData.success("成功删除"+num+"个");
        }
		return ResponseData.error("一个也没有删除掉");
    }

    /**
     * 批量删除key
     * @param pattern
     * @return 
     */
    public ResponseData deleteBatchKeys(final String pattern) {
    	ResponseData responseData = ResponseData.success();
        Set<Serializable> keys = redisTemplate.keys(pattern);
        
        Long num = 0L;
        if (keys.size() > 0) {
            num = redisTemplate.delete(keys);
        }
        if(num>0) {
        	return ResponseData.success("成功删除"+num+"个");
        }
        return ResponseData.error("一个也没有删除掉");
    }
    
    /**
     * 删除对应的value
     * @param key
     * @return 
     */
    public boolean remove(final String key) {
    	boolean flag = false;
        if (exists(key)) {
        	redisTemplate.delete(key);
        	flag = true;
        }
		return flag;
    }
    /**
     * 判断缓存中是否有对应的value
     * @param key
     * @return
     */
    public boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }
    /**
     * 读取缓存
     * @param key
     * @return
     */
    public ResponseData getCaheValue(final String key) {
    	ResponseData responseData = ResponseData.success();
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        if(null != operations.get(key)) {
        	responseData.setData(operations.get(key));
        	return responseData;
        }
        return ResponseData.error("查询不到有效结果");
    }
    /**
     * 哈希 添加
     * @param key
     * @param hashKey
     * @param value
     * @return 
     */
    public ResponseData addHashPut(String key, Student student){
        try {
			HashOperations<String, String, String> hash = redisTemplate.opsForHash();
			hash.put(key,String.valueOf(student.getId()),student.getName());
			return ResponseData.success("哈希 添加或修改成功");
		} catch (Exception e) {
			log.info("哈希 添加失败:"+e.getMessage());
			return ResponseData.error(e.getMessage());
		}
    }

    /**
     * 哈希获取数据
     * @param key
     * @param hashKey
     * @return
     */
    public ResponseData getHashValue(String key, Student student){
        ResponseData responseData = ResponseData.success();
    	HashOperations<String, Object, Object>  hash = redisTemplate.opsForHash();
    	Object object = hash.get(key,String.valueOf(student.getId()));
    	if(null != object) {
    		responseData.setData(object);
    		return responseData;
    	}
        return ResponseData.error("哈希获取数据失败");
    }

    /**
     * 列表添加
     * @param k
     * @param v
     */
    public ResponseData addList(String k,List<Student> stus){
    	ResponseData responseData = ResponseData.success();
        ListOperations<String, Object> list = redisTemplate.opsForList();
        Long num = list.rightPush(k,stus);
        if(num>0) {
        	return ResponseData.success("list添加成功");
        }
        return ResponseData.error("list添加失败");
    }

    /**
     * 列表获取
     * @param k
     * @param 0  size的第一个
     * @param -1 size的最后一个
     * @return
     */
    public ResponseData selectList(String k){
    	ResponseData responseData = ResponseData.success();
        ListOperations<String, Object> list = redisTemplate.opsForList();
        List<Object> lists = list.range(k,0,-1);
        if(null != lists && lists.size()>0) {
        	responseData.setData(lists);
        	return responseData;
        }
        return ResponseData.error("查询List失败");
    }

    /**
     * 集合添加
     * @param key
     * @param value
     */
    public ResponseData addSet(String key,List<Student> list){
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        Long num =0L;
        for(int i = 0; i<list.size();i++) {
        	num=set.add(key,list.get(i));
        	if(num>0) {
        		num++;
        		continue;
        	}
        	return ResponseData.error("set集合添加第"+num+"个时候失败");
        }
        return ResponseData.success("set集合添加成功,个数："+num);
    }

    /**
     * 集合获取
     * @param key
     * @return
     */
    public ResponseData selectSet(String key){
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        Set<Object> objects = set.members(key);
        if(null != objects && !objects.isEmpty()) {
            return ResponseData.success(objects);
        }
        return ResponseData.error("set集合查询失败");
    }

    /**
     * 有序集合添加
     * @param key
     * @param value
     * @param scoure
     */
    public ResponseData addZset(String key,List<Student> list){
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        boolean flag =false;
        for(int i =0;i<list.size();i++) {
        	flag = zset.add(key,list.get(i),i);
        	if(!flag) {
        		return ResponseData.error("添加第"+i+"笔数据的时候失败");
        	}
        }
        return ResponseData.success("添加数据成功");
    }

    /**
     * 有序集合获取
     * @param key
     * @param scoure
     * @param scoure1
     * @return
     */
    public ResponseData selectZset(String key){
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        //这里的0和1查询的是个范围区间,包含边值
        Set<Object> set = zset.rangeByScore(key, 0, 1);
        if(null != set && !set.isEmpty()) {
        	return ResponseData.success(set);
        }
        return ResponseData.error("有序集合获取失败");
    }
}

